import Vue from "vue";
import instance from "./axios";
import apiList from "../../http-api/index";
import store from "../../store/index";
import { Message } from "element-ui";

// 请求方法
const $http = async (apiName, params = {}) => {
  // 拿到当前api
  let currentApi = apiList[apiName];
  if (!currentApi) {
    return Promise.reject({
      msg: "接口未定义",
    });
  }

  // 是否登录
  if (!store.state.userToken && !["login"].includes(apiName)) {
    await store.dispatch("userLogin");
  }

  // 拼接URL 处理动态路游

  let url = params.route ? currentApi.url + params.route : currentApi.url;
  url = "/client" + url;
  params.route && delete params.route;

  // 设置请求头
  let headers = {
    "Content-Type": params.contentType || "application/json",
  };
  // 发送请求
  return new Promise((resolve, reject) => {
    axios(url, currentApi.method, params, headers)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 请求统一封装
const axios = (url, type, data, headers) => {
  let method = type.toUpperCase();
  if (method == "GET") {
    return instance.get(url, {
      params: data,
      headers,
    });
  }
  if (method == "POST") {
    return instance.post(url, data, { headers });
  }
  if (method == "PUT") {
    return instance.put(url, data, { headers });
  }
  if (method == "DELETE") {
    return instance.delete(url, {
      data,
      headers,
    });
  }
  return Promise.reject({
    msg: "当前仅支持 : GET,POST,PUT,DELETE请求,",
  });
};

Vue.prototype.$http = $http;
export default $http;
